import { CodeInfo, Market } from "@/assets/api/rtdatasubscriberservice_0_0_1";
import { defineStore } from "pinia";
import { reactive } from "vue";

export const useQuoteStore = defineStore("quote", () => {
  let code_index_map = {};

  const codeTags = reactive<{
    codeInfos: Array<CodeInfo>;
    tabs: Array<string>;
    tabIndex: number;
  }>({
    codeInfos: [
      {
        market: Market.SSE,
        code: "000001",
        trading_code: "",
        name: "上证指数",
        short_en: "",
        listed_date: 0,
        de_listed_date: 0,
        trading_hours: [],
        contract_multiple: 0,
        min_tick: 0,
      },
    ],
    tabs: ["上证指数"],
    tabIndex: 0,
  });

  code_index_map["上证指数"] = 0;
  const addCode = (codeInfo: CodeInfo) => {
    if (codeInfo.name in code_index_map) {
      codeTags.tabIndex = code_index_map[codeInfo.name];
      return;
    }
    codeTags.codeInfos.push(codeInfo);
    codeTags.tabs.push(codeInfo.name);
    codeTags.tabIndex = codeTags.tabs.length - 1;
    code_index_map[codeInfo.name] = codeTags.tabIndex;
  };

  const removeCode = (name: string) => {
    codeTags.tabIndex = 0;
    const index = code_index_map[name];
    codeTags.codeInfos.splice(index, 1);
    codeTags.tabs.splice(index, 1);
    delete code_index_map[name];
  };

  const getCurCodeInfo = () => {
    return codeTags.codeInfos[codeTags.tabIndex];
  };

  return {
    codeTags,
    getCurCodeInfo,
    addCode,
    removeCode,
  };
});
